package com.lingjtx.im.core.distribute;

import com.lingjtx.common.core.constant.Const;
import com.lingjtx.common.core.constant.MqConst;
import com.lingjtx.common.redis.service.IRedisService;
import com.lingjtx.common.thread.api.WebClientApi;
import com.lingjtx.im.core.handle.ImMessageHandle;
import com.lingjtx.im.core.protocol.MessageProto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class KefuMessage implements ImMessageHandle {

    private final WebClientApi webClientApi;
    private final IRedisService redisService;
    private final MessagePublisher publisher;

    public KefuMessage(WebClientApi webClientApi, IRedisService redisService, MessagePublisher publisher) {
        this.webClientApi = webClientApi;
        this.redisService = redisService;
        this.publisher = publisher;
    }

    @Override
    public void process(MessageProto.IMMessage message, byte version) {
        // 持久化客服消息
        publisher.publish(MqConst.IM_QUEUE_KEFU_CHAT, message);

        // 拉取客服坐席人员列表
        webClientApi.getKefuSeatIds(message.getReceiverId())
                .doOnError(error -> log.error("获取客服坐席人员列表失败，客服 ID={}: {}", message.getReceiverId(), error.getMessage(), error))
                .subscribe(members -> handleKefuMessageDispatch(members, message));
    }

    private void handleKefuMessageDispatch(List<Long> memberIds, MessageProto.IMMessage message) {
        // 客服消息发送规则：1、AI 客服回复；2、客户转人工时，提醒值班坐席人员查看消息记录；3、管理员接收消息（免打扰）
    }

    @Override
    public byte getImType() {
        return Const.IMMsgType.KEFU;
    }
}
